<?php
/**
 * 控制器公共类(基础类)文件
 */

namespace app\admin\controller;

use think\Controller;
use think\Request;

/**
 * 控制器基础类
 *
 * @category Admin
 * @package  Controller
 * @author   huwhois <huwhois@163.com>
 */

class Base extends Controller
{
    protected $uid;
    protected $uname;
    
    /**
     * 判断是否登陆，检查登陆者是否有权调用想应的控制器和操作
     * $request Tp5.0 的请求响应对象
     */
    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        //判断是否登陆
        if (!session('uid')) {
            $this->error('请登陆', 'login/index');
        }
        
        $this->uid = session('uid');
        $this->uname = session('uname');
        
        //菜单数据
        $data_menu = model('menu')->where('status', 1)
            ->field('id,pid,name,method')
            ->select();

        $data_menu = obj_tree($data_menu);

         //当前活动菜单id
         $controller = $request->controller();

         $menu_url = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $controller)).'/index';
         
         $mid = model('menu')->where('method', $menu_url)->value('pid');

        //权限检查,针对角色
        $c = strtolower($controller);
        $a = strtolower(request()->action());
        
        $user_role_id = model('admin_user')->where('id', $this->uid)->value('role_id');

        if (!$this->checkAuthor($user_role_id, $c, $a)) {
            $this->error('你无权进行此操作', 'index/index');
        }
        
        // 模板输出
        $this->assign("data_menu", $data_menu);
        $this->assign("mid", $mid);
        $this->assign('controller', $c);
        $this->assign('action', $a);

        //记录操作日志
        //$this->addLog();
    }

    /**
     * 权限检查
     */
    private function checkAuthor($user_role_id, $c, $a)
    {
        if (!$user_role_id) {
            return false;
        }
        //超级管理员不检查
        if ($user_role_id == 1) {
            return true;
        }

        // 根目录不检查
        if (preg_match('/^public_/', $a)) {
            return true;
        }

        // 首页不检查
        if ($c == 'index' && $a == 'index') {
            return true;
        }

        $per_ids = model('admin_role')->where('id', $user_role_id)->value('permission');

        $permission_test = model('permission')->field('id,pid,method')->select($per_ids);
        
        $permission_test = \obj_tree($permission_test);

        // 先找对应 controller, 再找对应 action,有就返回 true
        foreach ($permission_test as $value) {
            if ($value->method == $c) {
                foreach ($value->child as $val) {
                    if ($val->method == $a) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    /**
     * 记录日志
     */
    private function addLog()
    {

        $data = array();
        $data['querystring'] = request()->query()?'?'.request()->query():'';
        $data['m'] = request()->module();
        $data['c'] = request()->controller();
        $data['a'] = request()->action();
        $data['userid'] = $this->uid;
        $data['username'] = $this->uname;
        $data['ip'] = ip2long(request()->ip());
        $arr = array('Index/index','Log/index','Menu/index');
        if (!in_array($data['c'].'/'.$data['a'], $arr)) {
            db('admin_log')->insert($data);
        }
    }

    // 删除
    public function del($id = null)
    {
        if (Request::instance()->isAjax()) {
            if ($this->model->destroy($id)) {
                return ['code'=>2,'msg'=>config('msg.1003')];
            } else {
                $this->error(config('msg.1004'));
            }
        }
    }

    /**
     * topHome 置顶状态改变
     */
    public function top($id = '', $column = '', $value = 0)
    {
        if (Request::instance()->isAjax()) {
            // return ['code'=>0,'msg'=>'操作失败'];
            if ($this->model->save([$column => $value], ['id' => $id])) {
                return ['code'=>2, 'msg'=>config('msg.1003')];
            } else {
                return ['code'=>0,'msg'=>config('msg.1004')];
            }
        }
    }

    /**
     * 文章审核
     *
     * @param integer $id
     * @param integer $status
     * @return void
     */
    public function duty($id, $status = 0)
    {
        if (Request::instance()->isAjax()) {
            $time = time();

            $result = $this->model->save([
                'status'=>$status,
                'mtime'=>$time,
            ], ['id' => $id]);

            if ($result===false) {
                return ['code'=>0,'msg'=>config('msg.1004')];
            } else {
                return ['code'=>2, 'msg'=>config('msg.1003')];
            }
        }
    }
}
